package com.bawei.yuekao.fragment;


import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bawei.yuekao.R;
import com.bawei.yuekao.adapter.SongAdapter;
import com.bawei.yuekao.entity.Song;
import com.bawei.yuekao.service.MusicService;
import com.bawei.yuekao.sql.MusicHelper;
import com.bawei.yuekao.utils.SongsUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * A simple {@link Fragment} subclass.
 */
public class LocalMusicFragment extends Fragment {


    private TextView tv_curernt,tv_duration,tv_name;
    private TextView pop_tv_curernt,pop_tv_duration,pop_tv_name;
    private ImageView imageView,iv_pre,iv_play,iv_next,iv_mode;
    private ImageView pop_imageView,pop_iv_pre,pop_iv_play,pop_iv_next,pop_iv_mode,pop_iv_love,pop_fanhui;
    private SeekBar seekBar,pop_seekbar;
    private LinearLayout linearLayout;
    private MusicRecevicer musicRecevicer;

    private ListView listView;
    private SongAdapter songAdapter;
    private List<Song> list;
    private View view;

    private MusicService.MusicBinder musicBinder;
    private Timer timer;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicBinder = (MusicService.MusicBinder) service;
            //!!!!!!绑定成功后设置集合
            musicBinder.setList(list);
            //！！！！！绑定成功后开启定时器
            intiTimer();
            //!!!!!!!! 绑定成功后
            initRecevicer();
            //！！！ 设置点击
            initLitener();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };



    public LocalMusicFragment() {

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_local_music, container, false);
        initView();
        initbind();
        return view;
    }
    //注册广播
    private void initRecevicer() {
        musicRecevicer = new MusicRecevicer();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.music.pre");
        intentFilter.addAction("com.music.start");
        intentFilter.addAction("com.music.pause");
        intentFilter.addAction("com.music.next");
        intentFilter.addAction("com.music.ui");
        intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);//来电监听
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);//网络状态监听
        getActivity().registerReceiver(musicRecevicer,intentFilter);
    }

    //定时器
    private void intiTimer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                final int current = musicBinder.getCurrent();
                final int duration = musicBinder.getDuration();
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        seekBar.setMax(duration);
                        seekBar.setProgress(current);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");
                        tv_duration.setText(simpleDateFormat.format(duration));
                        tv_curernt.setText(simpleDateFormat.format(current));

                        if(pop_imageView != null){
                            pop_seekbar.setMax(duration);
                            pop_seekbar.setProgress(current);
                            pop_tv_duration.setText(simpleDateFormat.format(duration));
                            pop_tv_curernt.setText(simpleDateFormat.format(current));
                        }




                    }
                });
            }
        },0,100);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if(timer != null){
            timer.cancel();
        }
        if(musicRecevicer != null){
            getActivity().unregisterReceiver(musicRecevicer);
        }


    }

    //设置监听
    private void initLitener() {
        iv_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                musicBinder.pauseOrstart();
            }
        });

        iv_pre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                musicBinder.pre();
            }
        });
        iv_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                musicBinder.next();
            }
        });

        iv_mode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //切换模式  自己完成
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                musicBinder.play(position);
            }
        });
        //拖拽
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    musicBinder.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //弹窗
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final PopupWindow popupWindow = new PopupWindow(getActivity());
                popupWindow.setHeight(RelativeLayout.LayoutParams.MATCH_PARENT);
                popupWindow.setWidth(RelativeLayout.LayoutParams.MATCH_PARENT);
                View view = LayoutInflater.from(getActivity()).inflate(R.layout.popup_window, null);
                pop_imageView = view.findViewById(R.id.pop_iv);
                Glide.with(getActivity())
                        .load(musicBinder.getAlbum())
                        .transform(new CircleCrop())
                        .into(pop_imageView);
                pop_iv_play = view.findViewById(R.id.pop_iv_pause);
                pop_iv_play.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        musicBinder.pauseOrstart();
                    }
                });
                pop_iv_pre = view.findViewById(R.id.pop_iv_pre);
                pop_iv_pre.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        musicBinder.pre();
                    }
                });
                pop_iv_next = view.findViewById(R.id.pop_iv_next);
                pop_iv_next.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        musicBinder.next();
                    }
                });
                pop_seekbar = view.findViewById(R.id.pop_sb);
                pop_tv_curernt = view.findViewById(R.id.pop_tv_current);
                pop_tv_duration = view.findViewById(R.id.pop_tv_duration);
                pop_tv_name = view.findViewById(R.id.pop_tv_name);
                pop_tv_name.setText(musicBinder.getName()+"");
                pop_iv_love = view.findViewById(R.id.pop_love);
                pop_iv_love.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //收藏存储数据
                        MusicHelper musicHelper = new MusicHelper(getActivity());
                        SQLiteDatabase database = musicHelper.getWritableDatabase();
                        ContentValues contentValues = new ContentValues();
                        contentValues.put("name",musicBinder.getName());
                        contentValues.put("singer",musicBinder.getsinger());
                        contentValues.put("data",musicBinder.getData());
                        contentValues.put("album",musicBinder.getAlbum());
                        database.insert("music",null,contentValues);
                        Toast.makeText(getActivity(), "收藏成功", Toast.LENGTH_SHORT).show();
                    }
                });
                pop_fanhui = view.findViewById(R.id.pop_fanhui);
                pop_fanhui.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });
                popupWindow.setContentView(view);
                popupWindow.showAtLocation(v, Gravity.BOTTOM,0,0);
            }
        });
    }

    //绑定服务
    private void initbind() {
        Intent intent = new Intent(getActivity(), MusicService.class);
        getActivity().bindService(intent,serviceConnection,Context.BIND_AUTO_CREATE);
    }
    //find控件
    private void initView() {
        linearLayout = view.findViewById(R.id.ll);
        seekBar = view.findViewById(R.id.bar);
        tv_curernt = view.findViewById(R.id.tv_current);
        tv_duration = view.findViewById(R.id.tv_duration);
        tv_name = view.findViewById(R.id.tv_name);
        iv_mode = view.findViewById(R.id.iv_mode);
        iv_pre = view.findViewById(R.id.iv_pre);
        iv_next = view.findViewById(R.id.iv_next);
        iv_play = view.findViewById(R.id.iv_play);
        imageView = view.findViewById(R.id.iv);
        listView = view.findViewById(R.id.lv);
        list = SongsUtils.getSongs(getContext());
        songAdapter = new SongAdapter(list, getContext());
        listView.setAdapter(songAdapter);

    }

    class MusicRecevicer extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.music.pre".equals(intent.getAction())){
                musicBinder.pre();

            }else if("com.music.start".equals(intent.getAction())){
                musicBinder.start();

            }else if("com.music.pause".equals(intent.getAction())){
                musicBinder.pause();
            }else if("com.music.next".equals(intent.getAction())){
                musicBinder.next();

            }else if("com.music.ui".equals(intent.getAction())){
                //更新图片和文字
                Glide.with(getActivity())
                        .load(musicBinder.getAlbum())
                        .transform(new CircleCrop())
                        .into(imageView);
                tv_name.setText(musicBinder.getName());

                if(pop_imageView != null){
                    Glide.with(getActivity())
                            .load(musicBinder.getAlbum())
                            .transform(new CircleCrop())
                            .into(pop_imageView);
                    pop_tv_name.setText(musicBinder.getName());
                }


            }else if(TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(intent.getAction())){//来电
                TelephonyManager telephonyManager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
                telephonyManager.listen(new PhoneStateListener(){
                    @Override
                    public void onCallStateChanged(int state, String phoneNumber) {
                        super.onCallStateChanged(state, phoneNumber);
                        switch (state){
                            case TelephonyManager.CALL_STATE_RINGING://来电话
                                musicBinder.pause();
                                break;

                            case TelephonyManager.CALL_STATE_IDLE://挂断
                                musicBinder.start();
                                break;

                            case TelephonyManager.CALL_STATE_OFFHOOK://童话
                                musicBinder.pause();
                                break;

                        }
                    }
                },PhoneStateListener.LISTEN_CALL_STATE);

            }else if(ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())){//网络
                ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
                if(activeNetworkInfo != null && activeNetworkInfo.isConnected()){//有网
                    musicBinder.start();
                }else{//无网
                    musicBinder.pause();
                }
            }
        }
    }


}
